package com.mybatisplus.socket_test1;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: GongXl
 * @Date: 2021/3/2 09:56
 * @Description:
 */
public class TCPServer03 {
    public static List<MultiThreadServer> clients = new ArrayList<MultiThreadServer>();

    public static void main(String[] args) {
        ServerSocket server = null;
        try {
            server = new ServerSocket(8989);
            System.out.println("服务器启动成功");
        } catch (Exception e) {
            System.out.println("服务器启动出错");
        }
        Socket socket = null;
        try {
            while (true) {
                socket = server.accept();
                MultiThreadServer st = new MultiThreadServer(socket);
                clients.add(st);
                System.out.println("clients size:"+clients.size());
                //每个服务端会对应服务一个客户端
                Thread thread = new Thread(st);
                thread.start();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    /**
     * @Author GongXl
     * @Description 服务端广播给所有客户端的方法
     * @Date 2021/3/2 10:06
     * @Param [msg]
     * @return void
     **/
    public static void sendToAll(Socket whoSaySocket,String msg){
        for (int i = 0; i < clients.size(); i++) {
            MultiThreadServer multiThreadServer = clients.get(i);
            Socket socket = multiThreadServer.getSocket();
//            System.out.println(socket.getInetAddress());
//            System.out.println(socket.getLocalAddress());
//            System.out.println(socket.getLocalPort());
            //不广播给自己
            String whoSaySocketStr = whoSaySocket.getRemoteSocketAddress().toString();
            String socketStr = socket.getRemoteSocketAddress().toString();
            if(whoSaySocketStr.equals(socketStr)){
                continue;
            }
            /*if(null != sayIp && sayIp.equals(socket.getInetAddress().getHostAddress())
                    &&
                    sayPort == socket.getLocalPort()){
                continue;
            }*/
            try {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes());
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
            }
        }
    }
}